import React, { Component } from 'react'
import './index.css';
import axios from 'axios';

export default class Duanzi extends Component {
    //state 状态
    state = {
        duanzis: [] // 这里必须要用空数组来初始化, 不能使用 {}
    }

    render() {
        return (
            <div className="duanzi-container">
                <h2>段子列表</h2>
                <hr />
                <table border="1">
                    <thead>
                        <tr><td>ID</td><td>作者</td><td>段子内容</td></tr>
                    </thead>
                    <tbody>
                        {
                            this.state.duanzis.map(item => {
                                return <tr key={item.sid}>
                                    <td>{item.sid}</td>
                                    <td>{item.name}</td>
                                    <td>{item.text}</td></tr>
                            })
                        }
                    </tbody>
                </table>
            </div>
        )
    }

    //组件挂载完毕
    async componentDidMount(){
        document.body.style.background = '#efefef';
        document.body.style.backgroundImage = 'url(http://api.xiaohigh.com:8090/image/random)';
        document.body.style.backgroundSize = 'contain';
        try{
            //发送AJAX请求
            let result = await axios.get('https://api.apiopen.top/getJoke?type=text')
            // console.log(result);
            //保存段子数据
            this.setState({
                duanzis: result.data.result
            })
        }catch(e){
            alert('数据获取异常, 请稍后再试..');
        }
    }

    componentWillUnmount(){
        document.body.style.background = 'none';
    }
}
